<template>
 <div class="borrower">
      
    <el-card class="box-card" shadow="never">
       <div  style="margin-bottom:20px;">
         <!--v-if="operationLook === undefined"-->
          <el-button v-if="operationLook === undefined" v-permission="'system:contract:upload'" type="warning" size="small" @click="handleCreate" >上传合同</el-button>
        <el-button  type="warning" size="small" @click="exportData" >一键导出</el-button>
       </div>
      <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" size="small" @selection-change="handleSelectionChange" element-loading-text="正在查询中。。。" :header-cell-style="{background:'#F7F7F8',color:'#606266'}" fit highlight-current-row>

      <el-table-column type="selection" width="55"/>
      <el-table-column type="index" align="center" width="50" label="序号"/>
      <el-table-column align="center" label="合同名称" prop="name"/>
      <el-table-column align="center" label="上传时间" prop="uploadTime"/>
      <el-table-column align="center" label="签约时间" prop="signTime"/>

      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button  type="primary" size="mini" @click="uploadFile(scope.row)">打印</el-button> -->
          <el-button v-if="operationLook === undefined" v-permission="'system:contract:query'"  type="primary" size="small"  @click="handleUpdate(scope.row)">查看</el-button>
          <el-button v-if="operationLook === undefined"  v-permission="'system:contract:delete'"  size="small"  @click="deleteData(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" >
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 55%; margin-left:50px;">

        <el-form-item label="合同名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入合同名称"/>
        </el-form-item>
        <el-form-item label="签约时间" prop="signTime">
           <el-date-picker
                style="width:100%"
                v-model="dataForm.signTime"
                type="datetime"
                placeholder="选择签约时间"
                align="right"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
        </el-form-item>
         <el-form-item label="合同图片" prop="fileUrlList">
          <el-upload
            :action="uploadPath"
            :limit="5"
            :file-list="galleryFileList"
            :headers="headers"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-error="handleUploadError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card">
            <i class="el-icon-plus"/>
            <div slot="tip" class="el-upload__tip">只能上传.jpg,.jpeg,.png,.gif文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button size="small" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button size="small" v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogStatusPicEdit" :visible.sync="dialogFormVisiblePicEdit" :close-on-click-modal="false">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <el-dialog :title="dialogStatusPic" :visible.sync="dialogFormVisiblePic" :close-on-click-modal="false" width="20%">
       <div class="demo-image__preview">
        <el-image 
          style="width: 100px; height: 100px"
          :src="picUrlList[0]" 
          :preview-src-list="picUrlList"
          alt="点击查看大图">
        </el-image>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<style>
  .demo-image__preview{
    width: 100px;
    height: 100px;
    margin:0 auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
import { getToken } from '@/utils/auth'
import { uploadPath } from '@/api/projectFile'
import { deleteFile } from '@/api/file'
import { listContract,createContract,updateContract,deleteContract,exportContract } from '@/api/contract'

export default {
  name: 'contract',
  components: { },
  // 接受父组件的值
  props: {
     changeValue: undefined,
     projectId: undefined,
     operationLook: undefined
    },
  data() {
    return {
      uploadPath,
      defaultProjectId: undefined,
      appointNextTime:undefined,
      updateParam: undefined,
      list: undefined,
      total: 0,
      listLoading: false,
      options:[],
      picUrlList:[],
      fileIds:[],
      galleryFileList:[],
      value:undefined,
      dialogImageUrl: undefined,
      listQuery: {
        page: 1,
        limit: 10,
        projectId: this.projectId
      },
      contractIdList: [],
      dataForm: {
        name: undefined,
        signTime: undefined,
        fileIdList: [],
        projectId:this.projectId,
        remark:undefined,
        fileUrlList: []
      },
      dialogFormVisible: false,
      dialogFormVisiblePic: false,
      dialogFormVisiblePicEdit: false,
      dialogStatus: '',
      dialogStatusPic:'',
      dialogStatusPicEdit:'',
      data: [{
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        signTime: [
          { required: true, message: '请选择签约时间', trigger: 'blur' }
        ],
        signTime: [
          { required: true, message: '请选择签约时间', trigger: 'blur' }
        ],
      },
      downloadLoading: false,
      tableData: []
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': "Bearer-"+getToken()
      }
    }
  },
  created() {
   
    this.getList()
  },
  methods: {
        next() {
        if (this.active++ > 5) this.active = 0;
      },
     getList() {
       this.listLoading = true
      listContract(this.listQuery)
        .then(response => {
            this.list = response.data
            this.total = response.total
            this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
           this.listLoading = false
        })
    },
    resetForm() {
      this.dataForm = {
        name: undefined,
        signTime: undefined,
        fileIdList: [],
        projectId:this.projectId,
        remark:undefined,
        fileUrlList: []
      }
    },
    handleSelectionChange(val){
      let contractIdList = []
      for( let i = 0; i < val.length ; i++ ) {
        contractIdList.push(val[i].id)
      }
      this.contractIdList = contractIdList
      console.log(contractIdList)
    },
    handleCreate() {
      this.resetForm()
      this.galleryFileList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
        this.galleryFileList = []
        for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
          this.galleryFileList.push({
            url: this.dataForm.fileUrlList[i].fileUrl
          })
        }
    },
    exportData() {
        if( this.contractIdList.length === 0){
           this.$message.error("请选择合同")
           return false
        }
        exportContract(this.contractIdList)
            .then((res) => {
              this.$notify.success({
                title: '成功',
                message: '下载成功'
              })
              const content = res
            const blob = new Blob([content])
            const fileName = '合同打包下载.zip'
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
            })
            .catch(response => {
              console.log(response)
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
    },
    createData() {
      console.log(this.dataForm)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createContract(this.dataForm)
            .then(() => {
             this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '上传成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
       updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateContract(this.dataForm)
            .then(() => {
             this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
     uploadPicUrl: function(response) {
      this.dataForm.fileId = response.data.id
      this.dataForm.picUrl = response.data.fileUrl
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleUploadError(res){
       this.$message({
        type: 'error',
        message: '上传文件失败'
      })
    },
    handleGalleryUrl(response, file, fileList) {
       if(this.dataForm.fileUrlList === undefined){
        this.dataForm.fileUrlList = []
        this.dataForm.fileIdList = []
      }
      if (response.code === 20000) {
        this.dataForm.fileUrlList.push({id:response.data.id,fileUrl:response.data.fileUrl,fileName:response.data.fileName})
        this.dataForm.fileIdList.push({fileId:response.data.id,flag:false})
      }
      console.log(this.dataForm)
    },
    handleRemove: function(file, fileList) {
      console.log(file)
      for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.fileUrl
        }

        if (this.dataForm.fileUrlList[i].fileUrl === url) {
          deleteFile({fileId:this.dataForm.fileUrlList[i].id,contractId:this.dataForm.id})
            .then(() => {
            })
            .catch(response => {
            })
          this.dataForm.fileUrlList.splice(i, 1)
          this.dataForm.fileIdList.splice(i, 1)
          console.log(this.dataForm.fileIdList)
        }
      }
    },
    handlePictureCardPreview(file){
        this.dialogImageUrl = file.url
        this.dialogFormVisiblePicEdit = true
    },
    uploadFile(row) {
      this.dataForm = Object.assign({}, row)
      // this.dataForm.picUrl = undefined
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      console.log(this.dataForm)
    },
    deleteData(row) {
       this.$confirm('确定要删除此合同吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteContract({id:row.id})
            .then(() => {
              this.listLoading = true
              this.getList()
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }).catch(() => {
           this.$message("已取消删除")
        });

    },
  }
}
</script>
